package com.laomuji.android.mvvm.base

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.laomuji.android.mvvm.base.lifecycle.LifecycleFragment
import com.laomuji.android.mvvm.utils.ReflectionUtil
import org.greenrobot.eventbus.EventBus

/**
 * 所有Fragment的基类
 * @author laomuji666
 * @since 2024/2/20
 */
abstract class BaseFragment <VB : ViewBinding, VM : ViewModel> : LifecycleFragment(){
    /**
     * MVVM
     */
    open lateinit var viewBinding: VB
    open lateinit var viewModel: VM

    /**
     * 主线程handler
     */
    private var mainHandlerIsInit = false
    open val mainHandler: Handler by lazy {
        mainHandlerIsInit = true
        Handler(Looper.getMainLooper())
    }

    /**
     * 是否已经销毁过了
     */
    private var isCleared = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //恢复清理状态
        isCleared = false

        //注册EventBus
        if (isOpenEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        //初始化MVVM
        initViewBinding(inflater, container)
        initViewModel()

        //初始化页面和数据
        initView()
        initData()

        return viewBinding.root
    }

    override fun onDestroyView() {
        clearPage()
        super.onDestroyView()
    }

    /**
     * 结束Fragment时清理
     */
    private fun clearPage(){
        //不重复清理数据
        if(isCleared){
            return
        }
        isCleared = true

        //注销EventBus
        if (isOpenEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }

        //移除handler
        if(mainHandlerIsInit){
            mainHandler.removeCallbacksAndMessages(null)
        }
    }

    /**
     * 初始化ViewBinding
     */
    private fun initViewBinding(inflater: LayoutInflater, container: ViewGroup?) {
        val viewBindingCls = ReflectionUtil.getGenericsClass<VB>(javaClass, 0) as Class<VB>
        val method = viewBindingCls.getMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        )
        @Suppress("UNCHECKED_CAST")
        viewBinding = method.invoke(null,inflater,container,false) as VB
    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val genericsClass = ReflectionUtil.getGenericsClass<VM>(javaClass, 1)
            ?: throw RuntimeException("ViewModel init Failed!")
        viewModel = ViewModelProvider(this)[genericsClass]
    }

    /**
     * 初始化页面
     * 包括对页面的初始化和获取Intent的数据
     */
    protected abstract fun initView()

    /**
     * 初始化数据
     * 包括从后台获取数据和监听ViewModel
     */
    protected abstract fun initData()

    /**
     * 默认不使用EventBus
     * @return 是否开启EventBus
     */
    protected open fun isOpenEventBus(): Boolean = false
}